package com.l.web.master.login;

import com.l.web.master.system.user.User;
import org.apache.log4j.Logger;
import org.l.qiao.Form;
import org.l.qiao.LConstant;
import org.l.qiao.web.ControllerSupport;
import org.l.qiao.web.ResponseCode;
import org.l.qiao.web.ResponseInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Controller
public class LoginController extends ControllerSupport {
    private static final Logger LOGGER = Logger.getLogger(LoginController.class);
    @Autowired
    private LoginService loginService;

    @RequestMapping("login")
    public ModelAndView login(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {
        return new ModelAndView("login", modelMap);
    }

    @RequestMapping("auth")
    public void auth(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) throws IOException {
        Form form = getForm(request);
        HttpSession session = request.getSession();
        Login login = new Login();
        boolean result = form.getCluster(login);
        LOGGER.debug("登录信息：" + login + ",sessionCode=" + session.getAttribute(LConstant.SESSION_CAPTCHA));
        ResponseInfo rj = new ResponseInfo();
        Object vCode = session.getAttribute(LConstant.SESSION_CAPTCHA);

        if (result) {

            if (vCode == null || !vCode.toString().equalsIgnoreCase(login.getString(Login.CAPTCHA, ""))) {
                rj.setCode(ResponseCode.ERROR_CAPTCHA);
                session.removeAttribute(LConstant.SESSION_CAPTCHA);
            } else {
                User user = loginService.getUser(login);

                if (user.isEmpty()) {
                    rj.setCode(ResponseCode.ERROR_USERNAME_OR_PASSWORD);
                } else {
                    session.setAttribute(LConstant.SESSION_USER, user);
                    session.removeAttribute(LConstant.SESSION_CAPTCHA);
                    rj.setCode(ResponseCode.SUCCESS);
                }
            }

        } else {
            LOGGER.error("非法登录：" + login);
            rj.setCode(ResponseCode.FORM_ERROR);
        }

        out(response, rj);
    }

    @RequestMapping("logout")
    public void logout(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) throws IOException {
        request.getSession().removeAttribute(LConstant.SESSION_USER);
        response.sendRedirect("/");
    }
}
